package io.renren.modules.edu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.JacksonUtils;
import io.renren.modules.edu.dao.TEduCourseDao;
import io.renren.modules.edu.dto.TEduCourseDTO;
import io.renren.modules.edu.entity.TEduCourseEntity;
import io.renren.modules.edu.service.TEduCourseService;
import io.renren.modules.edu.service.TEduTeacherinfoService;
import io.renren.modules.edu.vo.EduCourseTableVO;
import io.renren.modules.edu.vo.TEduTeacherinfoVO;
import io.renren.modules.security.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课程表
 *
 * @author zwp zwp
 * @since 1.0.0 2022-07-11
 */
@Slf4j
@Service
public class TEduCourseServiceImpl extends ServiceImpl<TEduCourseDao, TEduCourseEntity> implements TEduCourseService {

    @Autowired
    private TEduTeacherinfoService tEduTeacherinfoService;

    @Override
    public List<EduCourseTableVO> courseList(Map<String, Object> params) {
        log.info("用户课程表数据(数据权限过滤)");
        // 获取当前用户
        Long userId = SecurityUser.getUserId();
        TEduTeacherinfoVO eduTeacherinfoVO = tEduTeacherinfoService.queryTeacherBySysUserId(userId);
        // 初始化课程表
        List<EduCourseTableVO> courseTableVOList = this.initEduCourseTable();
        // 获取学期
        String schoolTerm = (String) params.get("schoolTerm");
        if (StringUtils.isBlank(schoolTerm)) {
            return courseTableVOList;
        }
        // 获取专业
        String subject = (String) params.get("subject");
        if (StringUtils.isBlank(subject)) {
            return courseTableVOList;
        }
        // 根据条件获取课程表数据
        QueryWrapper<TEduCourseEntity> wrapper = new QueryWrapper<TEduCourseEntity>();
        // 用户不是超级管理员
        if(userId != Constant.SUPER_ADMIN) {
            wrapper.eq("edu_teacherinfo_id", eduTeacherinfoVO.getId());
        }
        wrapper.eq("school_term", schoolTerm);
        wrapper.like("subject", subject);
        List<TEduCourseEntity> eduCourseEntityList = this.baseMapper.selectList(wrapper);

        if (CollectionUtils.isEmpty(eduCourseEntityList)) {
            return courseTableVOList;
        }
        // 按照 节 分组
        Map<Integer, List<TEduCourseEntity>> classSectionMap = eduCourseEntityList.stream().collect(Collectors.groupingBy(e -> e.getClassSection()));
        // 填充数据
        courseTableVOList.forEach(e -> {
            List<TEduCourseEntity> entityList = classSectionMap.get(e.getClassSection());
            if (CollectionUtils.isNotEmpty(entityList)) {
                // 按照周进行升排序
                List<TEduCourseEntity> sortedByWeek = entityList.stream().sorted(Comparator.comparing(j -> j.getWeek())).collect(Collectors.toList());
                sortedByWeek.forEach(y -> {
                    if (StringUtils.isNotBlank(y.getCourseName())) {
                        TEduTeacherinfoVO tEduTeacherinfoVO = tEduTeacherinfoService.queryTeacherInfoById(y.getEduTeacherinfoId());
                        if (y.getWeek() == 1) {
                            JSONObject oneWeek = new JSONObject();
                            oneWeek.put("id",y.getId().toString());
                            oneWeek.put("courseName",y.getCourseName());
                            oneWeek.put("courseAddress",y.getCourseAddress());
                            oneWeek.put("teacherName",tEduTeacherinfoVO.getRealName());
                            e.setOneWeek(oneWeek);
                        }
                        if (y.getWeek() == 2) {
                            JSONObject twoWeek = new JSONObject();
                            twoWeek.put("id",y.getId().toString());
                            twoWeek.put("courseName",y.getCourseName());
                            twoWeek.put("courseAddress",y.getCourseAddress());
                            twoWeek.put("teacherName",tEduTeacherinfoVO.getRealName());
                            e.setTwoWeek(twoWeek);
                        }
                        if (y.getWeek() == 3) {
                            JSONObject threeWeek = new JSONObject();
                            threeWeek.put("id",y.getId().toString());
                            threeWeek.put("courseName",y.getCourseName());
                            threeWeek.put("courseAddress",y.getCourseAddress());
                            threeWeek.put("teacherName",tEduTeacherinfoVO.getRealName());
                            e.setThreeWeek(threeWeek);
                        }
                        if (y.getWeek() == 4) {
                            JSONObject fourWeek = new JSONObject();
                            fourWeek.put("id",y.getId().toString());
                            fourWeek.put("courseName",y.getCourseName());
                            fourWeek.put("courseAddress",y.getCourseAddress());
                            fourWeek.put("teacherName",tEduTeacherinfoVO.getRealName());
                            e.setFourWeek(fourWeek);
                        }
                        if (y.getWeek() == 5) {
                            JSONObject fiveWeek = new JSONObject();
                            fiveWeek.put("id",y.getId().toString());
                            fiveWeek.put("courseName",y.getCourseName());
                            fiveWeek.put("courseAddress",y.getCourseAddress());
                            fiveWeek.put("teacherName",tEduTeacherinfoVO.getRealName());
                            e.setFiveWeek(fiveWeek);
                        }
                    }
                });
            }
        });
        return courseTableVOList;
    }

    @Override
    public void addCourse(TEduCourseDTO dto) {
        log.info("增加用户课程表数据");
        // 获取当前用户
        Long userId = SecurityUser.getUserId();
        TEduTeacherinfoVO tEduTeacherinfoVO = tEduTeacherinfoService.queryTeacherBySysUserId(userId);
        dto.setEduTeacherinfoId(tEduTeacherinfoVO.getId());
        // 查询是否已经存在课程
        QueryWrapper<TEduCourseEntity> wrapper = new QueryWrapper<TEduCourseEntity>();
        wrapper.eq("week",dto.getWeek());
        wrapper.eq("class_section",dto.getClassSection());
        wrapper.eq("subject",dto.getSubject());
        wrapper.eq("school_term",dto.getSchoolTerm());
        int count = this.baseMapper.selectCount(wrapper);
        if (count != 0) {
            throw new RRException("课程冲突无法添加！");
        }
        // 转换
        TEduCourseEntity tEduCourseEntity = JacksonUtils.obj2pojo(dto, TEduCourseEntity.class);
        this.baseMapper.insert(tEduCourseEntity);
    }

    @Override
    public void deleteCourse(Long id) {
        log.info("删除用户课程表数据");
        this.baseMapper.deleteById(id);
    }

    /**
     * 初始化课程表
     * @return
     */
    private List<EduCourseTableVO> initEduCourseTable() {
        List<EduCourseTableVO> list = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            EduCourseTableVO eduCourseTableVO = new EduCourseTableVO();
            eduCourseTableVO.setClassSection(i +1);
            list.add(eduCourseTableVO);
        }
        return list;
    }
}
